package com.zyfdroid.mindnote2;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zyfdroid.mindnote2.utils.AppSettings;
import com.zyfdroid.mindnote2.utils.DocumentManager;
import com.zyfdroid.mindnote2.utils.DocumentEditingPositionManager;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {
    private ListView listMain;
    private LinearLayout emptyIndicator;
    private LinearLayout loadingIndicator;
    private ImageButton btnAdd;
    private void initUI(){
        listMain = (ListView)findViewById(R.id.listMain);
        emptyIndicator = (LinearLayout)findViewById(R.id.emptyIndicator);
        loadingIndicator = (LinearLayout)findViewById(R.id.loadingIndicator);
        btnAdd = findViewById(R.id.btnAdd);
        listMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DocumentManager.DocumentInfo info = (DocumentManager.DocumentInfo) parent.getAdapter().getItem(position);
                EditorActivity.startEdit(MainActivity.this,info);
            }
        });
        listMain.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final DocumentManager.DocumentInfo info = (DocumentManager.DocumentInfo) parent.getAdapter().getItem(position);
                List<String> menuItems = new ArrayList<>();
                if(info.isDone){
                    menuItems.add("移出已完成");
                    menuItems.add("彻底删除");
                }
                else{
                    menuItems.add("移动到已完成");
                }
                new AlertDialog.Builder(MainActivity.this).setTitle(info.title)
                        .setItems(menuItems.toArray(new String[0]), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(which == 0){
                                    if(info.isDone){
                                        DocumentManager.moveDocumentToActive(info);
                                    }
                                    else{
                                        DocumentManager.moveDocumentToDone(info);
                                    }
                                    loadData();
                                }
                                if(which == 1){
                                    new AlertDialog.Builder(MainActivity.this).setTitle("确认删除").setMessage("是否删除："+info.title)
                                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    DocumentManager.deleteDocument(info);
                                                    DocumentEditingPositionManager.removeDocumentPosition(MainActivity.this,info);
                                                    loadData();
                                                    Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                                }
                                            }).setNegativeButton(android.R.string.no,null).create().show();
                                }
                            }
                        }).create().show();
                return true;
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        setTitle("笔记列表");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return super.onCreateOptionsMenu(menu);
    }

    boolean showDone = false;

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData(){
        if(showDone){
            if(getActionBar()!=null){
                getActionBar().setHomeButtonEnabled(true);
                getActionBar().setDisplayHomeAsUpEnabled(true);
            }
            setTitle("已完成的笔记");
        }
        else{
            if(getActionBar()!=null){
                getActionBar().setHomeButtonEnabled(false);
                getActionBar().setDisplayHomeAsUpEnabled(false);
            }
            setTitle("笔记列表");
        }
        loadingIndicator.setVisibility(View.VISIBLE);
        new Thread(() -> {
            List<DocumentManager.DocumentInfo> infos = DocumentManager.listDocuments(showDone);
            runOnUiThread(()->{
                loadingIndicator.setVisibility(View.GONE);
                btnAdd.setVisibility(showDone ? View.GONE : View.VISIBLE);
                if(infos.size() == 0){
                    listMain.setVisibility(View.GONE);
                    emptyIndicator.setVisibility(View.VISIBLE);
                }
                else{
                    listMain.setVisibility(View.VISIBLE);
                    emptyIndicator.setVisibility(View.GONE);
                    listMain.setAdapter(new NoteAdapter(infos));
                }
            });
        }).start();
    }



    public void newDocument(View view) {
        EditorActivity.startEdit(this,DocumentManager.createNewDocument());
    }

    public void mnuShowDoneClick(MenuItem item) {
        item.setChecked(!item.isChecked());
        showDone = item.isChecked();
        loadData();
    }


    public void mnuToggleTransparent(MenuItem item) {
        item.setChecked(!item.isChecked());
        AppSettings.transparentWindow = item.isChecked();
        AppSettings.saveSettings(this);
        hWnd.postDelayed(this::recreate,300);

    }

    class NoteAdapter extends ArrayAdapter<DocumentManager.DocumentInfo>{

        public NoteAdapter( List<DocumentManager.DocumentInfo> objects) {
            super(MainActivity.this, R.layout.list_adapter, objects);
        }


        @Override
        public View getView(int position,  View convertView,  ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.list_adapter,null,false);
            }
            DocumentManager.DocumentInfo item = getItem(position);
            TextView tv1 = convertView.findViewById(android.R.id.text1);
            TextView tv2 = convertView.findViewById(android.R.id.text2);
            tv1.setText(item.title);
            tv2.setText(DocumentManager.dateFormat.format(item.lastModified));
            return convertView;
        }
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if(menu == null){
            return false;
        }
        menu.findItem(R.id.mnuMainShowCompleted).setChecked(showDone);
        menu.findItem(R.id.mnuMainTransparentWindow).setChecked(AppSettings.transparentWindow);
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public void onBackPressed() {
        if(showDone){
            showDone = false;
            loadData();

            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onNavigateUp() {
        if(showDone){
            showDone = false;
            loadData();

            return true;
        }
        return super.onNavigateUp();
    }

    public void mnuExportClick(MenuItem item) {
        startActivity(new Intent(this, BackupActivity.class));
    }
}